/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.anniversary.rest;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.anniversary.domain.Message;
import me.zhengjie.modules.anniversary.repository.MessageRepository;
import me.zhengjie.modules.anniversary.service.ImgUploadService;
import me.zhengjie.modules.anniversary.service.MessageService;
import me.zhengjie.modules.anniversary.service.dto.ImgResultDto;
import me.zhengjie.modules.anniversary.service.dto.MessageDto;
import me.zhengjie.modules.anniversary.service.dto.MessageQueryCriteria;
import me.zhengjie.modules.anniversary.service.impl.MessageServiceImpl;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @website https://el-admin.vip
 * @author Jiayin Wei
 * @date 2020-07-27
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "留言板管理")
@RequestMapping("/api/message")
public class MessageController {

    private final MessageService messageService;

    @Autowired
    private final MessageRepository messageRepository;

    private final FileProperties properties;


    private final ImgUploadService imgUploadService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    //@PreAuthorize("@el.check('message:list')")
    @AnonymousAccess
    public void download(HttpServletResponse response, MessageQueryCriteria criteria) throws IOException {
        messageService.download(messageService.queryAll(criteria), response);
    }

    @GetMapping("/findMessage")
    @Log("查询留言板1")
    @ApiOperation("查询留言板1")
    @AnonymousAccess
    public Object findMessage(Integer page,Integer size){
        List<Map<String,Object>> message = messageService.findMessage(PageRequest.of(page, size));
        return message;
    }

    @GetMapping("/findMessage1")
    @Log("查询留言板2")
    @ApiOperation("查询留言板2")
    @AnonymousAccess
    public Object findMessage1(Integer issueType, Integer page,Integer size){
        List<Message> message = messageRepository.findMessage1(issueType, PageRequest.of(page, size));
        if(message.size()!=0){
            for (Message name:message) {
                System.out.println("name:"+name.getCreateTime());
            }
        }
        return message;
    }

    /**
     * 图片的上传
     * @param multipartFile 上传保修的图片信息
     * @return 返回map的json键值
     */
    @ResponseBody
    @PostMapping("/uploadimg")
    @AnonymousAccess
    public String uploadimg(@RequestParam("multipartFile") MultipartFile multipartFile) {
        //new一个map对象
        Map<String, Object> map = new HashMap<String, Object>();
        //如果上传的图片是null
        if (multipartFile.isEmpty()) {
            //对map中result键添加值为false
            map.put("result",false);
            //对map中url键添加值为空
            map.put("url","");
            //并向页面返回
            return JSONObject.toJSON(map).toString();
        }
        //得到上传时的文件名
        String fileName = multipartFile.getOriginalFilename();
        //利用UUID创建一个随机且不重复的，名字
        String newName = UUID.randomUUID().toString();
        //获取系统文件分隔符，取出"."以下的所有信息（取后缀名）
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        //对上传的文件名取名（去掉后缀名）
        String name = fileName.substring(0,fileName.lastIndexOf("."));
        //将系统格式的时间转换为文本（字符）格式
        String nowDate = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
        try {
            //设置存储图片路径
            File uploadPath = new File(properties.getPath().getUpload(),"图片/" + nowDate + "/") ;
            //文件夹路径不存在
            if (!uploadPath.exists() && !uploadPath.isDirectory()) {
                System.out.println("+++mrdir:" + uploadPath);
                // 创建此抽象路径名指定的目录，包括所有必需但不存在的父目录。可以创建多级目录
                uploadPath.mkdirs();
            }
            //文件路径
            String nPath = uploadPath +"/"+ newName + "." + type;
            File newFile = new File(nPath);
            multipartFile.transferTo(newFile);
            String fileUrl = nowDate + "/" + newName + "." + type;
            //判断文件是否上传成功
            if (fileUrl !=null ||fileUrl!=""){
                System.out.println(name + " upload success");
                map.put("result",true);
                map.put("url",fileUrl);
            }else{
                System.out.println(name + " upload fail");
                map.put("result",false);
                map.put("url","");
            }
        } catch (IOException e) {
            map.put("result",false);
            map.put("url","");
            System.out.println(e.toString());
        }
        return JSONObject.toJSON(map).toString();
    }

    @GetMapping
    @Log("查询留言板")
    @ApiOperation("查询留言板")
    //@PreAuthorize("@el.check('message:list')")
    @AnonymousAccess
    public ResponseEntity<Object> query(MessageQueryCriteria criteria, @PageableDefault(sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable){
        System.out.println("pageable:"+pageable.getPageSize());
        System.out.println("criteria:"+criteria);
        return new ResponseEntity<>(messageService.queryAll(criteria,pageable),HttpStatus.OK);
    }


    @GetMapping(value = "/count")
    @ApiOperation("查询留言板数")
    public ResponseEntity<Object> count(){
        return new ResponseEntity<>(messageService.count(),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增留言板")
    @ApiOperation("新增留言板")
//    @PreAuthorize("@el.check('message:add')")
    @AnonymousAccess
    public ResponseEntity<Object> create(@Validated @RequestBody Message resources){
        return new ResponseEntity<>(messageService.create(resources),HttpStatus.CREATED);
    }

    @PostMapping("/create1")
    @Log("新增留言板1")
    @ApiOperation("新增留言板1")
//    @PreAuthorize("@el.check('message:add')")
    @AnonymousAccess
    public String create1(@RequestBody JSONObject param){

        try {
            JSONObject datas = param.getJSONObject("datas");
            Message message2 = JSONObject.parseObject(datas.toJSONString(), Message.class);
            //new一个map对象
            Map<String, Integer> map = new HashMap<String, Integer>();
            //new一个Message对象
            Message message = new Message();
            message.setUserId(Long.valueOf(message2.getUserId()));
            message.setName("表白母校");
            message.setCreateBy(message2.getCreateBy());  //发布人
            Timestamp ts = new Timestamp(System.currentTimeMillis());
            message.setCreateTime(ts);  //创建时间
            message.setIssueType(Long.valueOf(message2.getIssueType()));
            message.setIssueImags(message2.getIssueImags());
            message.setUserType(Integer.valueOf(message2.getUserType()));
            message.setContent(message2.getContent());
            message.setVerifyStatus(Integer.valueOf(message2.getVerifyStatus()));
            int i = messageRepository.insertMessage1(message);
            return String.valueOf(i);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "0";

    }

    @PutMapping
    @Log("修改留言板")
    @ApiOperation("修改留言板")
    //@PreAuthorize("@el.check('message:edit')")
    @AnonymousAccess
    public ResponseEntity<Object> update(@Validated @RequestBody Message resources){
        MessageDto oldMessage = messageService.findById(resources.getId());
        if(oldMessage != null && oldMessage.getVerifyStatus() == 0  && oldMessage.getVerifyStatus() != resources.getVerifyStatus())
        {
            resources.setReviewerId(SecurityUtils.getCurrentUserId());
        }
        messageService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除留言板")
    @ApiOperation("删除留言板")
    //@PreAuthorize("@el.check('message:del')")
    @DeleteMapping
    @AnonymousAccess
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        messageService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
